package com.ruoyi.business.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.business.domain.AcContractInfo;
import com.ruoyi.business.mapper.AcContractInfoMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.websocket.WebSocketUsers;
import com.ruoyi.system.domain.AcMessage;
import com.ruoyi.system.mapper.AcMessageMapper;
import com.ruoyi.system.service.IAcMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 用于存储用户之间的消息记录Controller
 *
 * @author wangxu19
 * @date 2025-03-24
 */
@RestController
@RequestMapping("/system/message")
public class AcMessageController extends BaseController
{
    @Autowired
    private IAcMessageService acMessageService;

    @Autowired
    private WarnTask warnTask;

    @Autowired
    private AcMessageMapper acMessageMapper;

    @Autowired
    private AcContractInfoMapper acContractInfoMapper;
    /**
     * 查询用于存储用户之间的消息记录列表
     */
   //("@ss.hasPermi('system:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(AcMessage acMessage)
    {
        startPage();
        List<AcMessage> list = acMessageService.selectAcMessageList(acMessage);
        return getDataTable(list);
    }

    /**
     * 导出用于存储用户之间的消息记录列表
     */
   //("@ss.hasPermi('system:message:export')")
    @Log(title = "用于存储用户之间的消息记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AcMessage acMessage)
    {
        List<AcMessage> list = acMessageService.selectAcMessageList(acMessage);
        ExcelUtil<AcMessage> util = new ExcelUtil<AcMessage>(AcMessage.class);
        util.exportExcel(response, list, "用于存储用户之间的消息记录数据");
    }

    /**
     * 获取用于存储用户之间的消息记录详细信息
     */
   //("@ss.hasPermi('system:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(acMessageService.selectAcMessageById(id));
    }

    /**
     * 新增用于存储用户之间的消息记录
     */
   //("@ss.hasPermi('system:message:add')")
    @Log(title = "用于存储用户之间的消息记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AcMessage acMessage)
    {
        int result = acMessageService.insertAcMessage(acMessage);
        warnTask.warnTask();
        return toAjax(result);
    }

    /**
     * 修改用于存储用户之间的消息记录
     */
   //("@ss.hasPermi('system:message:edit')")
    @Log(title = "用于存储用户之间的消息记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AcMessage acMessage)
    {
        ;
        //先执行更新，再执行warntask
       int result = acMessageService.updateAcMessage(acMessage);
        warnTask.warnTask();
        return toAjax(result);
    }

    /**
     * 删除用于存储用户之间的消息记录
     */
   //("@ss.hasPermi('system:message:remove')")
    @Log(title = "用于存储用户之间的消息记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        int result = acMessageService.deleteAcMessageByIds(ids);
        warnTask.warnTask();
        return toAjax(result);
    }
    /**
     * 更新消息websocket推送
     */
    @GetMapping("/warnTask")
    public AjaxResult warnTask() {
        AcMessage acMessage = new AcMessage();
        acMessage.setIsRead("0");
        List<AcMessage> list = acMessageMapper.selectAcMessageList(acMessage);
        WebSocketUsers.sendMessageToUsersByText(JSON.toJSONString(list));
        return AjaxResult.success(list);
    }

    /**
     *
     * 合同到期提醒
     * **/
    @GetMapping("/warnContractTask")
    public AjaxResult warnContractTask(){
        AcMessage acMessage = new AcMessage();
        acMessage.setIsRead("0");
        //合同10天内到期查询
        List<AcContractInfo> result =acContractInfoMapper.selectAcContractInfoByExpireDate();
        for (AcContractInfo acContractInfo : result) {
            // 新增：定义日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 修改：将 java.util.Date 转换为 LocalDateTime
            java.util.Date contractEndDate = acContractInfo.getContractEndDate();
            LocalDateTime localDateTime = contractEndDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            // 修改：将合同到期时间格式化为指定格式
            String formattedEndDate = formatter.format(localDateTime);
            acMessage.setContent("合同编号："+acContractInfo.getContractCode()+"，合同名称："+acContractInfo.getContractAssetName()+"，合同到期时间："+formattedEndDate);
            acMessage.setMessageType("合同到期提醒");
            acMessage.setDeptId(acContractInfo.getDeptId());
            acMessage.setAssetId(acContractInfo.getContractAssetId().toString());
            acMessage.setSenderId("1");
            //当前时间
            acMessage.setSendTime(formatter.format(LocalDateTime.now()));

            acMessage.setReservedField(acContractInfo.getContractCode());
            // 查询message表是否有该条数据
            AcMessage acMessageDev = new AcMessage();
            acMessageDev.setReservedField(acContractInfo.getContractCode());
            List<AcMessage>  acMessage1 = acMessageMapper.selectAcMessageList(acMessageDev);
            if (acMessage1.size()>0){
                acMessage.setId(acMessage1.get(0).getId());
                acMessageMapper.updateAcMessage(acMessage);
            }else{
                acMessageService.insertAcMessage(acMessage);
            }
        }
        List<AcMessage> list =   acMessageMapper.selectAcMessageList(acMessage);
        WebSocketUsers.sendMessageToUsersByText(JSON.toJSONString(list));
        return AjaxResult.success(list);
    }

}
